﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Base;
using System.Collections;
using System.Data.SqlClient;

namespace QLKS
{
    public partial class frmTaoPhieuThue : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _table = new DataTable();
        private DataTable _tableTemp = new DataTable();
        private bool _them;        
        public DTO.PhongDTO _phong = new DTO.PhongDTO();
        //public delegate void PassData(int num, int total);
        public frmTaoPhieuThue()
        {
            InitializeComponent();
            _table.BeginInit();
            _table.Columns.Add("MaKhachHang", typeof(int));
            _table.Columns.Add("TenKhachHang", typeof(string));
            _table.Columns.Add("MaLoaiKhach", typeof(int));
            _table.Columns.Add("CMND", typeof(string));
            _table.Columns.Add("DiaChi", typeof(string));                      
            _table.EndInit();
            _tableTemp = _table.Copy();            
            //DevExpress.Skins.SkinManager.EnableFormSkins();
            //DevExpress.UserSkins.BonusSkins.Register();            
        }
        /// <summary>
        /// Enable hoặc disable các control
        /// </summary>
        /// <param name="edit">Disable input</param>
        /// <param name="clear">Xóa trống các input</param>
        public void SetControl(bool edit, bool clear)
        {
            gridControl1.Enabled = !edit;
            #region TextBoxs

            txtAddress.Properties.ReadOnly = !edit;
            txtName.Properties.ReadOnly = !edit;
            txtID.Properties.ReadOnly = !edit;
            lkeCategory.Properties.ReadOnly = !edit;
            
            #endregion
            btnInsert.Enabled = !edit;
            btnSave.Enabled = edit;
            btnAbort.Enabled = edit;
            if (gridView1.FocusedRowHandle > -1 && gridControl1.Enabled)
            {
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;                             
            }
            else
            {
                btnUpdate.Enabled = false;
                btnDelete.Enabled = false;                
            }
            #region ClearTexboxs

            if (clear)
            {
                txtAddress.Text = string.Empty;
                txtName.Text = string.Empty;
                txtID.Text = string.Empty;
                lkeCategory.EditValue = null;                
            }

            #endregion
        }
        /// <summary>
        /// Nếu _them = true là end-user chọn insert;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsert_Click(object sender, EventArgs e)
        {
            SetControl(true, true);
            txtID.Focus();
            _them = true;
        }
        private void frmTaoPhieuThue_Load(object sender, EventArgs e)
        {
            txtPhong.Text = _phong.TenPhong;
            //txtLoaiPhong.Text = _phong.MaLoaiPhong.ToString();
            dteNgayThue.EditValue = DateTime.Now;
            repositoryItemLookUpEdit1.DataSource = BUS.LoaiKhachHangBUS.SelectAll().Tables[0];
            repositoryItemLookUpEdit1.ValueMember = "MaLoaiKhach";
            repositoryItemLookUpEdit1.DisplayMember = "TenLoaiKhach";

            gridControl1.DataSource = _table;
            _tableTemp= BUS.KhachHangBUS.SelectAll().Tables[0];
            txtID.Properties.DataSource = _tableTemp;
            txtID.Properties.ValueMember = "CMND";
            txtID.Properties.DisplayMember = "CMND";
            
            lkeCategory.Properties.DataSource = BUS.LoaiKhachHangBUS.SelectAll().Tables[0];
            lkeCategory.Properties.ValueMember = "MaLoaiKhach";
            lkeCategory.Properties.DisplayMember = "TenLoaiKhach";
            SetControl(false, false);
        }
        private void GetDataRow()
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row != null)
            {
                txtName.Text = row[1].ToString();
                lkeCategory.EditValue = row[2];
                txtID.Text = row[3].ToString();
                txtAddress.Text = row[4].ToString();
            }
        }
        /// <summary>
        /// Lấy Row end-user Focus để gán vào các textbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            SetControl(false, false);
            GetDataRow();
        }

        /// <summary>
        /// Nếu _them=false nghĩa là end-user nhấn sửa
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            _them = false;
            SetControl(true, false);
        }
        
        /// <summary>
        /// Hủy thao tác thêm hoặc sửa và bỏ validate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbort_Click(object sender, EventArgs e)
        {
            var al = new ArrayList((ICollection)dxValidationProvider1.GetInvalidControls());
            foreach (Control c in al)
            {
                dxValidationProvider1.RemoveControlError(c);
            }
            SetControl(false, false);
            GetDataRow();
        }

        /// <summary>
        /// Validate dữ liệu nhập và xem là insert hay update (và thực hiện)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
                return;
            
            DTO.KhachHangDTO khachhang = new DTO.KhachHangDTO()
            {                
                TenKhachHang = txtName.Text,
                MaLoaiKhach = (int)lkeCategory.EditValue,
                Cmnd = txtID.Text,
                DiaChi = txtAddress.Text
            };           
            
            try
            {
                if (_them)
                {
                    string _Id = txtID.GetColumnValue("MaKhachHang").ToString();
                    if (_Id == string.Empty)
                    {
                        int id = BUS.KhachHangBUS.Insert(khachhang);
                        _table.Rows.Add(new object[]
                                       {
                                           id, txtName.Text,lkeCategory.GetColumnValue("MaLoaiKhach").ToString(), txtID.Text,
                                           txtAddress.Text
                                       });    
                    }
                    else
                    {

                        _table.Rows.Add(new object[]
                                       {
                                           _Id, txtName.Text,lkeCategory.GetColumnValue("MaLoaiKhach").ToString(), txtID.Text,
                                           txtAddress.Text
                                       });           
                    }                        
                }
                else
                {
                    khachhang.MaKhachHang = Convert.ToInt32(gridView1.GetDataRow(gridView1.FocusedRowHandle)[0]);
                    BUS.KhachHangBUS.Update(khachhang);
                    DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);                    
                    row[1] = txtName.Text;
                    row[2] = lkeCategory.GetColumnValue("MaLoaiKhach");
                    row[3] = txtID.Text;
                    row[4] = txtAddress.Text;                    
                }
                //gridControl1.DataSource = _table;
            }
            catch (SqlException ex)
            {
                string str = String.Format("Lỗi: {0}", ex.Message);
                MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SetControl(false, false);
        }

        /// <summary>
        /// Xóa Selected records
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle > -1)
            {
                int[] selectedRows = gridView1.GetSelectedRows();
                int countRows = gridView1.SelectedRowsCount;
                if (
                    MessageBox.Show(String.Format("Bạn muốn xóa {0} khách hàng??", countRows), "Thông Báo!",
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    for (int i = 0; i < countRows; i++)
                    {
                        BUS.ChiTietPhieuThueBUS.Delete((Int32)gridView1.GetDataRow(selectedRows[i])[0]);
                    }
                    gridView1.DeleteSelectedRows();
                }
            }
            else
            {
                MessageBox.Show("Không có khách hàng để xóa!", "Thông Báo!");
            }
        }

        /// <summary>
        /// Thoát và xóa dữ liệu chương trình để giải phóng bộ nhớ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (_table.Rows.Count > 0)
            {
                DTO.PhieuThuePhongDTO phieuThue = new DTO.PhieuThuePhongDTO() { MaPhong = _phong.MaPhong, NgayThuePhong = DateTime.Parse(dteNgayThue.EditValue.ToString()) };
                int id = BUS.PhieuThuePhongBUS.Insert(phieuThue);
                DTO.ChiTietPhieuThueDTO ctPhieuThue = new DTO.ChiTietPhieuThueDTO();
                foreach (DataRow row in _table.Rows)
                {
                    ctPhieuThue.MaPhieuThue = id;
                    ctPhieuThue.MaKhachHang = Convert.ToInt32(row["MaKhachHang"]);
                    BUS.ChiTietPhieuThueBUS.Insert(ctPhieuThue);
                }
                _phong.TinhTrangPhong = 1;
                BUS.PhongBUS.Update(_phong);                
            }
            _table.Clear();
            GC.Collect();
            Close();
        }

        private void txtID_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            if (txtID.Text != txtID.EditValue.ToString())
            {
                (txtID.Properties.DataSource as DataTable).Rows.Add(
                new object[]
                                       {
                                           null, null,null, txtID.Text,
                                           null
                                       });
                //_table.Rows.Add(new object[]
                //                       {
                //                           null, null,null, txtID.Text,
                //                           null
                //                       });
                e.Handled = true;                
            }
        }

        private void txtID_KeyUp(object sender, KeyEventArgs e)
        {            
            if (txtID.EditValue==null || txtID.Text != txtID.EditValue.ToString())
            {
                txtName.EditValue = string.Empty;
                txtAddress.EditValue = string.Empty;
                lkeCategory.EditValue = null;
            }
            else
            {
                txtName.EditValue = txtID.GetColumnValue("TenKhachHang");
                txtAddress.EditValue = txtID.GetColumnValue("DiaChi");
                lkeCategory.EditValue = txtID.GetColumnValue("MaLoaiKhach");                
            }
        }
    }
}